<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- card 带阴影效果的容器 -->
      <el-card class="dept-card">
        <!-- 公司名称
        row 和 col 都是elementUI提供的布局组件
        row：表示行，支持flex布局，只需要给组件添加type=flex即可
        col：表示列表，一行分为24列，可以通过span属性设置每一列占的比例
         -->
        <template />
        <TreeTool :bool="true" :data="company" @addEvent="addDept" @delEvent="delDept" />
        <!-- 部门列表 -->
        <!-- tree组件的使用
        data:渲染的数据源
        default-expand-all:是默认展开的所有节点 true表示展开,false关闭
        props:用于修改一下默认配置的
        label:设置渲染内容所代表的属性名 -->
        <el-tree :data="treeData" default-expand-all :props="{ label: 'name' }">
          <template v-slot="{ data }">
            <TreeTool :data="data" :bool="true" @addEvent="addDept" @delEvent="delDept" @editEvent="editEpart" />
          </template>
        </el-tree>
      </el-card>
      <el-dialog
        :title="formData.id?'编辑部门':'新增部门'"
        :visible="showDialog"
        @close="closeFn"
      >
        <el-form ref="form" :model="formData" label-width="100px" :rules="rules">
          <el-form-item label="部门名称" prop="name">
            <el-input v-model="formData.name" placeholder="1-50个字符" />
          </el-form-item>
          <el-form-item label="部门编码" prop="code">
            <el-input v-model="formData.code" placeholder="1-50个字符" />
          </el-form-item>
          <el-form-item label="部门负责人" prop="manager">
            <el-select v-model="formData.manager">
              <el-option
                v-for="item in userList"
                :key="item.id"
                :label="item.username"
                :value="item.username"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="部门介绍" prop="introduce">
            <el-input v-model="formData.introduce" type="textarea" placeholder="1-300个字符" />
          </el-form-item></el-form>
        <template v-slot:footer>
          <el-row type="flex" justify="center">
            <el-button @click="closeFn">取 消</el-button>
            <el-button type="primary" @click="submit">确 定</el-button>
          </el-row>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getDepartments, addDepartments, delDepartments, departmentDetail, updataDepartments } from '@/api/departments'
import TreeTool from './componeets/tree-tool.vue'
import { userSimble } from '@/api/employees'
export default {
  components: { TreeTool },
  data() {
    const checkCode = (rule, val, callback) => {
      let isRepeat
      if (this.formData.id) {
        // 区别编辑和新增
        isRepeat = this.depts.filter(item => item.id !== this.formData.id)
      } else {
        isRepeat = this.depts.every(item => item.code !== val)
      }
      if (!isRepeat) {
        callback(`部门编码${val}和已经存在的编码重复了`)
      } else {
        callback()
      }
    }
    const checkName = (rule, val, callback) => {
      let sameDept
      if (this.formData.id) {
        sameDept = this.depts.filter(item => item.id !== this.formData.id)
      } else {
        // 筛选出同级部门
        sameDept = this.depts.filter(item => item.pid !== this.formData.pid)
      }
      const isRepeat = sameDept.every(item => item.name !== val)
      if (!isRepeat) {
        callback(`部门名称${val}和已经存在的部门名称重复了!`)
      } else {
        callback()
      }
    }
    return {
      company: {
        name: '传智教育',
        manager: '负责人',
        id: ''
      },
      formData: {
        name: '',
        code: '',
        manager: '',
        introduce: '',
        pid: ''
      },
      treeData: [],
      depts: [],
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码长度为1-50个字符' },
          // 设置校验规则，判断部门名称是否重复
          { validator: checkName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码长度为1-50个字符' },
          // 设置校验规则，判断编码是否重复
          { validator: checkCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码长度为1-50个字符' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '部门编码长度为1-300个字符' }
        ]
      },
      // 控制弹框,true为显示，false为隐藏
      showDialog: false,
      userList: []
    }
  },
  async created() {
    // 获取部门列表
    this.getDepartments()
    // 获取员工列表
    const res = await userSimble()
    console.log(res)
    this.userList = res.data.data
  },
  methods: {
    async getDepartments() {
      const res = await getDepartments()
      console.log(res)
      // 保存公司名字
      this.company.name = res.data.data.companyName
      // 保存部门列表
      this.depts = res.data.data.depts
      this.treeData = this.listToTree(res.data.data.depts, '')
    },
    // 列表转树形结构
    listToTree(list, id) {
      // 先找一级部门
      // treeList用于保存找到的一级结构
      const treeList = []
      list.forEach(item => {
        if (item.pid === id) {
          treeList.push(item)
          // 在寻找二级结构
          // 代码优化
          item.children = this.listToTree(list, item.id)
        }
      })
      return treeList
    },
    // 新增部门
    addDept(val) {
      console.log('新增', val)
      this.formData.pid = val.id
      this.showDialog = true
    },
    // 编辑部门
    async editEpart(val) {
      this.showDialog = true
      const res = await departmentDetail(val.id)
      this.formData = res.data.data
    },
    // 删除部门
    delDept(val) {
      this.$confirm('是否确定删除？', '提示', {
        type: 'warning'
      }).then(async() => {
        await delDepartments(val.id)
        // 调用接口,刷新列表
        this.getDepartments()
      }).catch(() => {
        console.log('点击了取消按钮')
      })
    },
    submit() {
      // 表单校验
      this.$refs.form.validate(async(bool) => {
        if (bool) {
          if (this.formData.id) {
            await updataDepartments(this.formData)
          } else {
            // 新增部门
            await addDepartments(this.formData)
          }
          // 关闭弹窗
          this.closeFn()
          // 刷新部门列表
          this.getDepartments()
        }
      })
    },
    closeFn() {
      this.showDialog = false
      this.formData = {
        name: '',
        code: '',
        manager: '',
        introduce: '',
        pid: ''
      }
      // 重置校验规则
      this.$refs.form.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.dept-card {
  padding: 30px 40px;
  font-size: 14px;

  .el-tree {
    margin-top: 20px;
  }
}
</style>
